package com.rui.study.micro.scheduler.service.impl;

import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.lite.spring.api.SpringJobScheduler;
import com.dangdang.ddframe.job.reg.base.CoordinatorRegistryCenter;
import com.rui.study.micro.scheduler.job.BulletinJob;
import com.rui.study.micro.scheduler.model.Task;
import com.rui.study.micro.scheduler.service.BulletinService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.concurrent.ConcurrentHashMap;

import static com.rui.study.micro.scheduler.util.Constant.BULLETIN_TASK;

@Service
public class BulletinServiceImpl implements BulletinService {

    private static final Logger LOGGER = LoggerFactory.getLogger(BulletinServiceImpl.class);

    @Autowired
    private CoordinatorRegistryCenter registryCenter;

    @Autowired
    private BulletinJob bulletinJob;

    @Resource(name = "redisTemplate")
    private HashOperations<Serializable, String, String> redisOps;

    private ConcurrentHashMap<String, SpringJobScheduler> schedulerMap = new ConcurrentHashMap<>();


    @Override
    public void buildScheduler(Task task) {
        String name = task.getTaskId();
        String cron = task.getCron();

        // 定义作业核心配置
        JobCoreConfiguration simpleCoreConfig = JobCoreConfiguration.newBuilder(name, cron, 1).build();
        // 定义SIMPLE类型配置
        SimpleJobConfiguration simpleJobConfig = new SimpleJobConfiguration(simpleCoreConfig, BulletinJob.class.getCanonicalName());
        // 定义Lite作业根配置
        LiteJobConfiguration simpleJobRootConfig = LiteJobConfiguration.newBuilder(simpleJobConfig).build();

        // 构建调度器，并启动
        SpringJobScheduler scheduler = new SpringJobScheduler(bulletinJob, registryCenter, simpleJobRootConfig, bulletinJob);
        schedulerMap.put(name, scheduler);
        scheduler.init();
    }

    @Override
    public void clearTask(String jobName) {
        /* 1.删除Redis中的任务id */
        if (redisOps.delete(BULLETIN_TASK, jobName) == 1) {
            LOGGER.info("Removed task [{}] from Cache", jobName);
        }

        /* 2.关闭调度器 */
        SpringJobScheduler scheduler = schedulerMap.remove(jobName);
        if (scheduler != null) {
            scheduler.getSchedulerFacade().shutdownInstance();
            LOGGER.info("Shutdown the scheduler of task [{}] from registry", jobName);
        }

        /* 3.移除注册表中的任务节点 */
        registryCenter.remove("/" + jobName);
        LOGGER.info("Removed task [{}] from registry", jobName);
    }
}
